package com.ruoyi.web.controller.water;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.waterEnity.ImageEntity;
import com.ruoyi.system.domain.waterEnity.ProductInfoBO;
import com.ruoyi.system.domain.waterEnity.SortEntity;
import com.ruoyi.system.service.waterService.ImageService2;
import com.ruoyi.system.service.waterService.ProductService;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Controller
@RequestMapping("/water")
public class ProductController extends BaseController {
    @Autowired
    private ProductService productService;
    @Autowired
    private ImageService2 imageService2;
    @Autowired
    private ServerConfig serverConfig;
    private String prefix = "water/product";
    /**
     * 商品管理首页
     *
     * @return
     */
    @RequiresPermissions("water:product:view")
    @RequestMapping("/product")
    public String product(ModelMap map) {
        List<ProductInfoBO> products = productService.selectAllProduct();
        List<SortEntity> sl = productService.selectSortList();
        map.put("sl",sl);
        System.out.println(products);
        return "water/product/post";
    }
    /**
     * 商品列表
     *
     * @return
     */
    @RequiresPermissions("water:product:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(String product_id,String product_name,String state,String sort) {
        startPage();
        List<ProductInfoBO> list = productService.selectAllProductByCondition(product_id,product_name,state,sort);
        return getDataTable(list);
    }


    /**
     * 跳转到新增商品页面
     *
     * @return
     */
    @RequiresPermissions("water:product:view")
    @GetMapping("/add")
    public String add() {
        return prefix + "/add1";
    }

    /**
     * 新增商品
     *
     * @param request
     * @param productInfoBO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("water:product:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(HttpServletRequest request, ProductInfoBO productInfoBO) {
        System.out.println(productInfoBO);
        try {
            //判断商品名称是否重复
            String num2 = productService.checkProduct_name(productInfoBO);
            if (num2 != null) {
                return error("新增商品'" + productInfoBO.getProduct_name() + "'失败，商品名称已存在");
            } else {
                int num = productService.insertProduct(productInfoBO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error("添加主商品出错了哦！！");
        }
        return success();


    }

    /**
     * 分类
     *
     * @param
     * @return
     */
    @RequiresPermissions("water:product:view")
    @PostMapping("/sortList")
    @ResponseBody
    public String sortList() {
        List<SortEntity> sl = productService.selectSortList();
        Map output = new TreeMap();
        output.put("sl", sl);
        JSONObject jsonObject = JSONObject.fromObject(output);
        return jsonObject.toString();
    }

    /**
     * 跳转到添加子商品页面
     *
     * @param
     * @return
     */
    @RequiresPermissions("water:product:view")
    @Log(title = "增加子商品", businessType = BusinessType.OTHER)
    @GetMapping("/addChildren/{id}")
    public String addChildren(@PathVariable("id") int id, Model model) {
        System.out.println(id);
        model.addAttribute("id", id);
        return prefix + "/addChildProduct";
    }

    /**
     * 跳转到子商品页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("water:product:childProduct")
    @GetMapping("/showChildren/{id}")
    public String showChildren(@PathVariable("id") int id, Model model) {
        System.out.println(id);
        model.addAttribute("id", id);
        return prefix + "/childProduct";
    }
    /**
     * 跳转到编辑子商品页面
     *
     * @param child_id
     * @param model
     * @return
     */
    @RequiresPermissions("water:product:view")
    @GetMapping("/editChildren/{child_id}")
    public String editChildren(@PathVariable("child_id") int child_id, Model model) {
        System.out.println(child_id);
        model.addAttribute(child_id);
        return prefix + "/editChildProduct";
    }

    /**
     * 加载子商品列表
     *
     * @return
     */
    @RequiresPermissions("water:product:list")
    @PostMapping("/listNorm/{id}")
    @ResponseBody
    public TableDataInfo listNorm(@PathVariable("id") int id) {
        System.out.println(id);
        startPage();
        List<ProductInfoBO> list = productService.selectAllNorm(id);
        System.out.println(list);
        return getDataTable(list);
    }

    /**
     * 添加子商品
     *
     * @param id
     * @param request
     * @param productInfoBO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("water:product:add")
    @PostMapping("/addChildProduct/{id}")
    @ResponseBody
    public AjaxResult addChildProduct(@PathVariable("id") int id, HttpServletRequest request, ProductInfoBO productInfoBO) {
        System.out.println(productInfoBO);
        MultipartFile headImg = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        try {
            if (isMultipart) {
                MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
                headImg = multipartRequest.getFile("headImg");
                System.out.println(headImg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error("上传图片失败！！");
        }
        try {
            if (headImg != null || !headImg.equals("null")) {
                String img = imageService2.upload(headImg);
                System.out.println(img);
                if (img != null) {
                    img = img.replace("http://10.0.3.61/group1/M00/00/00/", "");
                    System.out.println(img);
                    productInfoBO.setImg(img);
                    productInfoBO.setProduct_id(id);
                } else {
                    return error("文件格式不对，应该上传图片哦！！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error("上传图片失败！！");
        }

        //事务回滚，insertNorm数据库中出错，insertProduct回滚
        try {
            //判断商品名称是否重复
            String num2 = productService.checkProduct_name(productInfoBO);
            if (num2 != null) {
                return error("新增商品'" + productInfoBO.getProduct_name() + "'失败，商品名称已存在");
            }
            //规格插入是否成功
            int price = productInfoBO.getPrice() * 100;
            productInfoBO.setPrice(price);
            int num1 = productService.insertNorm(productInfoBO);
            if (num1 < 0) {
                return error("商品规格部分出错了哦！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//加上之后，如果insert2()抛了异常,//insert1()是会回滚的
        }
        return success();
    }


    /**
     * 查询子商品信息
     * @param child_id
     * @return
     */
    @RequiresPermissions("water:product:select")
    @PostMapping("/childProduct_info/{child_id}")
    @ResponseBody
    public String childProduct_info(@PathVariable("child_id") int child_id) {
        System.out.println(child_id);
        //根据id查找子商品
        ProductInfoBO productInfoBO = productService.selectChildProductById(child_id);
        Map out = new TreeMap();
        out.put("pb", productInfoBO);
        JSONObject jsonObject = JSONObject.fromObject(out);
        return jsonObject.toString();
    }

    /**
     * 编辑子商品信息
     *
     * @param id
     * @return
     */
    @RequiresPermissions("water:product:edit")
    @PostMapping("/editChildProduct/{id}/{product_id}")
    @ResponseBody
    public AjaxResult editChildren(@PathVariable("id") int id, @PathVariable("product_id") int product_id, HttpServletRequest request, ProductInfoBO productInfoBO) {
        //编辑子商品信息
        productInfoBO.setChild_id(id);
        productInfoBO.setProduct_id(product_id);
       int  price = productInfoBO.getPrice()*100;
       productInfoBO.setPrice(price);
        //当前端有传图片时，上传图片
        //上传商品图片
        MultipartFile headImg = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        try {
            if (isMultipart) {
                MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
                headImg = multipartRequest.getFile("headImg");
                System.out.println(headImg);
                if (headImg != null) {
                    //上传图片
                    String img = imageService2.upload(headImg);
                    System.out.println(img);
                    if (img != null) {
                        productInfoBO.setImg(img);
                        int flag = productService.updateNorm(productInfoBO);
                        if (flag > 0) {
                            return success();
                        } else {
                            return error("修改商品数据失败！！");
                        }
                    } else {
                        //图片没有更改时，不上传图片
                        productInfoBO.setImg(null);
                        int flag = productService.updateNorm(productInfoBO);
                        if (flag > 0) {
                            return success();
                        } else {
                            return error("修改商品数据失败！！");
                        }
                    }

                }else{
                    //图片没有更改时，不上传图片
                    productInfoBO.setImg(null);
                    int flag = productService.updateNorm(productInfoBO);
                    if (flag > 0) {
                        return success();
                    } else {
                        return error("修改商品数据失败！！");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error("获取图片失败！");
        }
    return success();
    }
        /**
         * 删除主商品
         * @param ids
         * @return
         */
        @PostMapping("/removeProduct")
        @ResponseBody
        public AjaxResult removeProduct (String ids){
            int num = productService.deleteProductAndNorm(ids);
            if (num > 0) {
                return success("删除商品成功！！！");
            } else {
                return error("删除商品失败！");
            }
        }

        /**
         * 商品状态修改
         */

        @Log(title = "商品状态", businessType = BusinessType.UPDATE)
        @RequiresPermissions("water:product:edit")
        @Transactional
        @PostMapping("/changeStatus")
        @ResponseBody
        public AjaxResult changeStatus (ProductInfoBO productInfoBO )
        {
            // roleService.checkRoleAllowed(role);  不允许操作超级管理员
            //根据子商品id，查找主商品id
            //检查主商品状态，如果主商品状态为下架则不能对子商品进行操作；
            ProductInfoBO productInfoBO1 = productService.checkProductState(productInfoBO);
            if (productInfoBO1 == null){
                int num = productService.updateProductState(productInfoBO);
                //下架子商品，检查子商品里面的状态，若没有商品上架，则修改主商品的状态
                List<ProductInfoBO> productInfoBOList = productService.checkChildProductState(productInfoBO);
                if (productInfoBOList.size()==0){   //没有商品上架
                    //修改主商品的状态
                    Integer  productState = 0;
                    productInfoBO.setId(productInfoBO.getProduct_id());
                    productInfoBO.setProductState(productState);
                    int num1 = productService.updateProductState1(productInfoBO);
                    if (num1>0){
                        System.out.println("主商品状态同步成功！");
                    }else{
                        System.out.println("主商品状态同步失败！");
                    }
                }
                if (num > 0) {
                    return success();
                } else {
                    return error();
                }
            }else{
                return error("主商品为下架状态哦，不能对子商品进行上架！");
            }
        }
    /**
     * 修改主商品下全部商品状态
     */
    @Log(title = "商品状态", businessType = BusinessType.UPDATE)
    @RequiresPermissions("water:product:edit")
    @PostMapping("/changeProductStatus")
    @ResponseBody
    public AjaxResult changeProductStatus (ProductInfoBO productInfoBO )
    {
        int num = productService.updateProductState1(productInfoBO);
        if (num > 0) {
            return success();
        } else {
            return error();
        }

    }
    /**
     * 修改库存
     */
    @RequiresPermissions("water:product:edit")
    @PostMapping("/changeStock")
    @ResponseBody
    public  AjaxResult changeStock(ProductInfoBO productInfoBO){
        int num = productService.updateProductStock(productInfoBO);
        if (num>0){
            return success();
        }else{
            return error();
        }
    }
    /**
     * 删除子商品
     * @param ids
     * @return
     */
    @PostMapping("/removeChildProduct")
    @ResponseBody
    public AjaxResult removeChildProduct (String ids){
        int num = productService.deleteChildProduct(ids);
        if (num > 0) {
            return success("删除商品成功！！！");
        } else {
            return error("删除商品失败！");
        }
    }
    /**
     * 根据分类id查询分类名称
     */
    @RequiresPermissions("water:product:view")
    @PostMapping("/selectSortBySort_id/{sort_id}")
    @ResponseBody
    public String selectSortBySort_id(@PathVariable("sort_id") int sort_id) {
        //List<SortEntity> sl = productService.selectSortList();
        SortEntity sortEntity = productService.selectSortBySort_id(sort_id);
        Map output = new TreeMap();
        output.put("sortEntity", sortEntity);
        JSONObject jsonObject = JSONObject.fromObject(output);
        return jsonObject.toString();
    }
    /**
     *   跳转到商品详情图
     */
    @RequestMapping("/editImg/{id}")
    public String editImg(@PathVariable("id") int id,ModelMap map){
        //根据id，查找商品图片
        map.put("id",id);
        return prefix+"/editImg";
    }
    /**
     * 商品详情图上传
     */


    /**
     * 通用上传请求
     */
    @PostMapping("/common/uploadImg/{id}")
    @ResponseBody
    public AjaxResult uploadFile(@PathVariable("id") int id, @RequestParam("fileDataList") MultipartFile[] fileDataList,HttpServletRequest request) throws Exception
    {
        System.out.println(id);
        ImageEntity imageEntity = new ImageEntity();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        List<MultipartFile> myfiles = multipartRequest.getFiles("myfiles");
        int i =0;
        for (MultipartFile file1 :fileDataList){

            if (file1.isEmpty()){
                error("文件未上传");
            }else{
                String img = imageService2.upload(file1);
                i++;
                imageEntity.setImg(img);
                imageEntity.setProduct_id(id);
                imageEntity.setSequence(i);
                int num = productService.productImage(imageEntity);
                if (num<0){
                    return error();
                }
                return success();
            }
        }

//        System.out.println(file);
//            // 上传文件路径
//            String filePath = Global.getUploadPath();
//            // 上传并返回新文件名称
////            MultipartFile f : file
//            for (int i=0;i<file.length;i++ ){
//                System.out.println(i);
//                String img = imageService2.upload(file[i]);
//                ImageEntity imageEntity =null;
//                imageEntity.setImg(img);
//                imageEntity.setProduct_id(id);
//                imageEntity.setSequence(i);
//                int num = productService.productImage(imageEntity);
//                if (num<0){
//                    return error();
//                }
//            }
//            return success();

        return success();
    }
}